/**
 * 2017年5月3日
 */
package util.io;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

import pojo.dto.services.DocumentVector;

/**
 * @author Alex
 *
 */
public final class LibSVMWriter {
	final File target;
	final DocumentVector [] v;
	boolean showDocId = false;
	
	/**
	 * 
	 * @param f要写入的文件,这应该指向一个文件,而不是一个目录
	 */
	public LibSVMWriter(File f,DocumentVector [] iter) {
		this.target = f;
		this.v = iter;
	}
	public boolean write(){
		try {
			writeToFile(this.target);
			return true;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}
	
	private void writeToWriterWithID(Writer w) throws IOException{
		for(DocumentVector x:v){
			if(x.getDocLabel().equals("unknow")){
				writeDocWithID(w, x);
			}else{
				writeDocWithTag(w, x);
			}
			
		}
	}
	private void writeToFile(File f) throws IOException{
		try(BufferedWriter bw = new BufferedWriter(new FileWriter(f))){
			writeToWriterWithID(bw);
		}
	}
	/**
	 * 这个 \r\n在不同的系统上可能存在兼容性
	 * 因为linux windows macos上面换行符不同
	 * 
	 * @param w
	 * @param dv
	 * @throws IOException
	 */
	private void writeDocWithID(Writer w,DocumentVector dv) throws IOException{
			w.write(dv.getDocId());
			w.write("\t");
			String s = dv.getVector().toVecSVMLine();
			w.write(s);
			w.write("\r\n");
		
	}
	private void writeDocWithTag(Writer w,DocumentVector dv) throws IOException{
		w.write(dv.getDocLabel());
		w.write("\t");
		w.write(dv.getDocId());
		w.write("\t");
		String s = dv.getVector().toVecSVMLine();
		w.write(s);
		w.write("\r\n");
	}
}
